import { Table, Button, message, PaginationProps } from 'antd';
import React, { useEffect, useState, useRef } from 'react';
import { env } from '@/utils/data';
import { syncGetGroups } from '@/services/gitlab';
import { searchApi, deleteApi, getProjectList } from '@/request/gitlab';
import { colWidth } from '@/utils/tools';
import { useHeight } from '@/utils/hooks/height';
import PageTitle from '@/components/pageTitle';
import ProjectSearch from './search';
import ProjectEdit from './edit';
import Styles from './index.module.css';

const map = {
  left: '左侧',
  right: '右侧',
};

const columns = (handleDelete, handleEdit) => [
  {
    title: '项目ID',
    dataIndex: 'id',
    width: 100,
    align: 'center',
  },
  {
    title: '项目名称',
    dataIndex: 'name',
    width: 200,
  },
  {
    title: '项目分组',
    dataIndex: ['namespace', 'name'],
    width: 200,
    showSorterTooltip: false,
    sorter: (a, b) => a?.namespace?.name.localeCompare(b?.namespace?.name),
  },
  {
    title: '项目地址',
    dataIndex: 'web_url',
    width: 300,
    render(text) {
      return (
        <a href={text} target="_blank" className="tableTitle">
          {text}
        </a>
      );
    },
  },
  {
    title: '使用环境',
    dataIndex: 'envs',
    width: 200,
    render(text) {
      if (!text) return <span>-</span>;
      const res = env.filter((item) => text.includes(item.value)).map((item) => item.label);
      return res.map((item) => (
        <span className="env-box" key={item}>
          {item}
        </span>
      ));
    },
  },
  {
    title: '是否展示在环境使用记录',
    dataIndex: 'showInMind',
    align: 'center',
    width: 200,
    render(text, record) {
      if (text === 1) {
        return <span>{map[record.position]}</span>;
      }
      return <span>不展示</span>;
    },
  },
  {
    title: '操作',
    dataIndex: 'edit',
    width: 80,
    fixed: 'right',
    render: (text: any, record: any) => (
      <>
        {/* <Button onClick={() => handleDelete(record)} type="link" danger>
          删除
        </Button> */}
        <span onClick={() => handleEdit(record)} className={Styles.link_div} style={{ color: '#1890ff' }}>
          编辑
        </span>
      </>
    ),
  },
];

const Index = ({ groups }) => {
  const [searchParams, setSearchParams] = useState({});
  const [list, setList] = useState<any[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const { height } = useHeight(300);
  const [pagination, setPagination] = useState<PaginationProps>(() => ({
    current: 1,
    pageSize: 10,
    onChange(page, pageSize) {
      setPagination({
        ...pagination,
        current: page,
      });
      setSearchParams({
        page,
        pageSize,
      });
    },
  }));
  const dialog = useRef<any>({});

  const handleSearch = async (params) => {
    setLoading(true);
    try {
      const ret: any = await getProjectList(params);
      setPagination({
        ...pagination,
        total: ret.total,
      });
      if (ret.list) {
        setList(ret.list);
      }
    } catch (err: any) {
      console.log(err);
    } finally {
      setLoading(false);
    }
  };

  const handleFinish = (value: any) => {
    setPagination({
      ...pagination,
      current: 1,
    });
    setSearchParams({
      ...searchParams,
      ...value,
      page: 1,
      pageSize: pagination.pageSize,
    });
  };

  const handleReset = () => {
    setPagination({
      ...pagination,
      current: 1,
    });
    setSearchParams({
      page: 1,
      pageSize: pagination.pageSize,
    });
  };

  useEffect(() => {
    handleSearch(searchParams);
  }, [searchParams]);

  const handleEdit = ({ id }) => {
    dialog.current.handleOpen(id);
  };

  const handleDelete = async (record) => {
    try {
      const res = await deleteApi({
        id: record.id,
      });
      if (res) {
        message.success('删除成功');
        setSearchParams({});
      } else {
        message.error('删除失败');
      }
    } catch (err: any) {
      console.log(err);
    }
  };

  const handleOk = () => {
    handleSearch(searchParams);
  };

  const myColumns: any = columns(handleDelete, handleEdit);

  return (
    <div>
      <PageTitle title="项目列表" />
      <ProjectSearch handleFinish={handleFinish} handleReset={handleReset} groups={groups} />
      <Table columns={myColumns} pagination={pagination} dataSource={list} rowKey="id" scroll={{ x: colWidth(myColumns), y: height }} loading={loading}></Table>
      <ProjectEdit ref={dialog} groups={groups} handleOk={handleOk} />
    </div>
  );
};

export default Index;

// 获取项目组列表
export async function getStaticProps() {
  const res = await syncGetGroups();
  return {
    props: {
      groups: res,
    },
  };
}
